package com.tiamo.traders.myfilter;

import com.tiamo.traders.entity.ResultModel;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 过滤器：
 * 1、实现Filter接口
 * 2、urlPatterns：设置过滤器的拦截路径
 * 3、过滤器本身是一个特殊的servlet，采用回调实现
 * */
//@WebFilter(filterName = "LoginFilter", urlPatterns = "/*")
public class LoginFilter implements Filter {
    /**
     * 过滤器初始化，只能初始化一次。
     * */
    public void init(FilterConfig config) throws ServletException {
        //System.out.println("过滤器初始化");
    }

    /**
     * doFilter：过滤器执行逻辑
     * */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        System.out.println("登录过滤器");

        //System.out.println("过滤器执行逻辑");
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;


        //获取客户端请求路径
        String url = req.getRequestURI();
        //判定url中是否以/back开头，
        //如果url以back开始，需要判定用户是否登录，否则直接放行
        boolean isBackLogin = url.startsWith("/tiamo");
        if(isBackLogin){ //需要判定用户是否登录
            HttpSession session = req.getSession();
            Object userInfo = session.getAttribute("userinfo");
            if(userInfo != null){
                //如果用户已经登录，放行客户端请求
                chain.doFilter(request, response);
            } else {
                /*if(url.endsWith(".html") || url.endsWith(".js") || url.endsWith(".css") || url.endsWith(".png") || url.endsWith(".jpg")){
                    resp.sendRedirect("/login/login.html");
                    //req.getRequestDispatcher("/login/login.html").forward(req, resp);
                } else {
                    PrintWriter writer = resp.getWriter();
                    resultModel.setCode(-2);
                    resultModel.setMsg("还未登录");
                    writer.write(JSON.toJSONString(resultModel));
                    writer.close();
                }*/
                resp.sendRedirect("/login/login.html");
            }
        } else { //不需要判定用户是否登录
            chain.doFilter(request, response);
        }

    }

    /**
     * 过滤器销毁时执行，只执行一次
     * */
    public void destroy() {
        System.out.println("过滤器的销毁");
    }


}
